import { app, BrowserWindow, shell, ipcMain, Menu } from 'electron'
import { release } from 'node:os'
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { update } from './update'

// 禁用Windows 7的GPU加速
if (release().startsWith('6.1')) app.disableHardwareAcceleration()

// 设置Windows 10+通知的应用程序名称
if (process.platform === 'win32') app.setAppUserModelId(app.getName())

if (!app.requestSingleInstanceLock()) {
  app.quit()
  process.exit(0)
}

// 删除electron security警告
// 此警告仅用于开发目的，可以忽略
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

// 定义应用路径
export const ROOT_PATH = {
  // /dist
  dist: join(__dirname, '../..'),
  // /dist or /public
  public: join(__dirname, app.isPackaged ? '../..' : '../../../public'),
}

let win: BrowserWindow | null = null
// 开发服务器URL
const url = process.env.VITE_DEV_SERVER_URL as string

// 如果是打包后的应用，使用相对路径
function resolveHtmlPath() {
  if (app.isPackaged) {
    // 打包后的路径
    const htmlPath = resolve(__dirname, '../../dist/index.html')
    console.log('打包后HTML路径:', htmlPath)
    return htmlPath
  } else {
    // 开发环境下的路径
    return join(ROOT_PATH.dist, 'index.html')
  }
}

// 创建应用菜单
function createMenu() {
  const template = [
    {
      label: '文件',
      submenu: [
        { 
          label: '新建', 
          accelerator: 'CmdOrCtrl+N',
          click: () => {
            // 处理新建操作
            win?.webContents.send('menu-action', { action: 'new-file' });
          }
        },
        { 
          label: '打开', 
          accelerator: 'CmdOrCtrl+O',
          click: () => {
            win?.webContents.send('menu-action', { action: 'open-file' });
          }
        },
        { 
          label: '保存', 
          accelerator: 'CmdOrCtrl+S',
          click: () => {
            win?.webContents.send('menu-action', { action: 'save-file' });
          }
        },
        { type: 'separator' },
        { 
          label: '退出', 
          accelerator: 'CmdOrCtrl+Q',
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: '地图',
      submenu: [
        { 
          label: '查看地图', 
          click: () => {
            win?.webContents.send('menu-action', { action: 'view-map' });
          }
        },
        { 
          label: '搜索位置', 
          click: () => {
            win?.webContents.send('menu-action', { action: 'search-location' });
          }
        }
      ]
    },
    {
      label: '设置',
      submenu: [
        { 
          label: '应用设置', 
          click: () => {
            win?.webContents.send('menu-action', { action: 'app-settings' });
          }
        },
        { 
          label: '用户偏好', 
          click: () => {
            win?.webContents.send('menu-action', { action: 'user-preferences' });
          }
        }
      ]
    },
    {
      label: '关于',
      submenu: [
        { 
          label: '关于软件', 
          click: () => {
            win?.webContents.send('menu-action', { action: 'about-app' });
          }
        },
        { 
          label: '检查更新', 
          click: () => {
            win?.webContents.send('menu-action', { action: 'check-updates' });
          }
        }
      ]
    }
  ];

  if (process.env.NODE_ENV === 'development') {
    // 在开发模式下添加开发者工具
    (template[3].submenu as any).push(
      { type: 'separator' },
      { 
        label: '开发者工具', 
        accelerator: 'F12',
        click: () => {
          win?.webContents.toggleDevTools();
        }
      }
    );
  }

  const menu = Menu.buildFromTemplate(template as any);
  Menu.setApplicationMenu(menu);
}

async function createWindow() {
  win = new BrowserWindow({
    title: 'Electron多功能工具',
    icon: join(ROOT_PATH.public, 'favicon.ico'),
    width: 1000,
    height: 680,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      // 由于我们的预加载脚本，这里可以安全地使用NodeJS API
      nodeIntegration: true,
      contextIsolation: true,
      webSecurity: false, // 临时禁用以调试加载问题
    },
    // 使用无边框窗口和透明效果，增加现代感
    frame: false,
    titleBarStyle: 'hidden',
    transparent: false,
  })

  // 设置窗口加载完成后执行的操作
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', new Date().toLocaleString())
    console.log('窗口加载完成，发送消息到渲染进程')
  })

  // 添加错误事件监听
  win.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    console.error('加载失败:', errorCode, errorDescription)
  })

  // 使得在应用内点击链接时用默认浏览器打开
  win.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith('https:')) shell.openExternal(url)
    return { action: 'deny' }
  })

  // 创建应用菜单
  createMenu();

  // 加载Vite开发服务器URL或生产环境的HTML文件
  if (app.isPackaged) {
    const htmlPath = resolveHtmlPath()
    console.log('应用已打包，加载文件:', htmlPath)
    console.log('应用路径:', app.getAppPath())
    console.log('__dirname:', __dirname)
    
    try {
      // 直接使用file://协议加载
      if (win) {
        const fileUrl = `file://${htmlPath}`
        console.log('尝试使用URL加载:', fileUrl)
        win.loadURL(fileUrl).catch(err => {
          console.error('URL加载失败，尝试使用loadFile:', err)
          return win?.loadFile(htmlPath)
        })
      }
    } catch (err) {
      console.error('加载过程中发生错误:', err)
    }
    
    // 即使在打包模式下也打开开发者工具进行调试
    win?.webContents.openDevTools()
  } else {
    win?.loadURL(url)
    // 打开开发者工具
    win?.webContents.openDevTools()
  }
}

// 当app准备就绪时创建窗口
app.whenReady().then(createWindow)

// 激活app时，如果没有窗口则创建新窗口
app.on('activate', () => {
  const allWindows = BrowserWindow.getAllWindows()
  if (allWindows.length) {
    allWindows[0].focus()
  } else {
    createWindow()
  }
})

// 当所有窗口关闭时退出应用，除了macOS
app.on('window-all-closed', () => {
  win = null
  if (process.platform !== 'darwin') app.quit()
})

// 在此处添加IPC处理程序
ipcMain.handle('open-win', (_, arg) => {
  const childWindow = new BrowserWindow({
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: true,
      contextIsolation: true,
    },
  })

  if (app.isPackaged) {
    childWindow.loadFile(resolveHtmlPath(), { hash: arg.hash })
  } else {
    childWindow.loadURL(`${url}#${arg.hash}`)
  }
})

// 处理文件操作的IPC
ipcMain.handle('file-operation', async (_, arg) => {
  // 这里可以处理文件的打开、保存等操作
  console.log('File operation:', arg);
  return { success: true, message: '文件操作成功' };
});

// 处理窗口控制
ipcMain.on('window-control', (_event, command) => {
  if (!win) return
  
  console.log('接收到窗口控制命令:', command)
  
  switch (command) {
    case 'minimize':
      win.minimize()
      break
    case 'maximize':
      if (win.isMaximized()) {
        win.unmaximize()
      } else {
        win.maximize()
      }
      break
    case 'close':
      win.close()
      break
  }
})
